package internal

import (
	"text/template"

	"gitee.com/hailib/mytree/errs"
	"gitee.com/hailib/mytree/gen"
	"go.uber.org/zap/buffer"
)

// ParseTemplate 解析 sql 模板
func ParseTemplate(temp string, data interface{}) (string, Error) {
	t := template.New("branch")
	t, err := t.Parse(temp)
	if err != nil {
		return "", errs.New(errs.UnexceptError, 210901171720, "parse temp error, error: %s, temp: %s", err.Error(), temp)
	}

	buf := buffer.Buffer{}
	err = t.Execute(&buf, data)
	if err != nil {
		return "", errs.New(errs.UnexceptError, 210901171754, "execute temp error, error: %s, temp: %s", err.Error(), temp)
	}
	return buf.String(), nil
}

// ReadTemplate 读取创建表格的 sql
func ReadTemplate(branchTable string, leafTable string) (branch string, leaf string, err Error) {
	data := make(map[string]string)
	data["BranchTable"] = branchTable
	data["LeafTable"] = leafTable

	buf, aerr := gen.Asset("asset/branch.sql")
	if aerr != nil {
		return branch, leaf, errs.New(errs.UnexceptError, 210901171452, "read asset/branch error, err: %s", aerr.Error())
	}

	branch, err = ParseTemplate(string(buf), data)
	if err != nil {
		return branch, leaf, err
	}

	buf, aerr = gen.Asset("asset/leaf.sql")
	if aerr != nil {
		return branch, leaf, errs.New(errs.UnexceptError, 210901171452, "read asset/leaf error, err: %s", aerr.Error())
	}
	leaf, err = ParseTemplate(string(buf), data)
	return branch, leaf, err
}
